import { getUserInfo } from "@/api/user"
import { defineStore } from "pinia"
import { ref, computed, watch } from "vue"
import cookie from "js-cookie"

export const useUserStore = defineStore("user", () => {
	const loadingInstance = ref(null)

	const userInfo: any = ref({
		uuid: "",
		nickName: "",
		headerImg: "",
		authority: {},
		sideMode: "dark",
		activeColor: "var(--el-color-primary)",
		baseColor: "#fff"
	})
	const token = ref(window.localStorage.getItem("token") || cookie.get("x-token") || "")
	const setUserInfo = (val: any) => {
		userInfo.value = val
	}

	const setToken = (val: any) => {
		token.value = val
	}

	const ResetUserInfo = (value = {}) => {
		userInfo.value = {
			...userInfo.value,
			...value
		}
	}
	/* 获取用户信息*/
	const GetUserInfo = async() => {
		const res: any = await getUserInfo()
		if (res.code === 0) {
			setUserInfo(res.data.userInfo)
		}
		return res
	}

	const mode = computed(() => userInfo.value.sideMode)
	const sideMode = computed(() => {
		if (userInfo.value.sideMode === "dark") {
			return "#191a23"
		} else if (userInfo.value.sideMode === "light") {
			return "#fff"
		} else {
			return userInfo.value.sideMode
		}
	})
	const baseColor = computed(() => {
		if (userInfo.value.sideMode === "dark") {
			return "#fff"
		} else if (userInfo.value.sideMode === "light") {
			return "#191a23"
		} else {
			return userInfo.value.baseColor
		}
	})
	const activeColor = computed(() => {
		return "var(--el-color-primary)"
	})

	watch(() => token.value, () => {
		window.localStorage.setItem("token", token.value)
	})

	return {
		userInfo,
		token,
		ResetUserInfo,
		GetUserInfo,
		mode,
		sideMode,
		setToken,
		baseColor,
		activeColor,
		loadingInstance,
	}
})
